package com.camartsApp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camartsApp.Util.Response;
import com.camartsApp.common.ResultVO;
import com.camartsApp.entity.Photo;
import com.camartsApp.entity.PhotoUser;
import com.camartsApp.mapper.PhotoMapper;

import com.camartsApp.common.PhotoUserVO;
import com.camartsApp.mapper.PhotoUserMapper;
import com.camartsApp.mapper.UserInfoMapper;
import com.camartsApp.mapper.UserMapper;
import com.camartsApp.service.PhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;


@Service
public class PhotoServiceImpl implements PhotoService {

    @Autowired
    private PhotoMapper photoMapper;

    @Autowired
    private PhotoUserMapper photoUserMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    private static final Logger logger = LoggerFactory.getLogger(PhotoServiceImpl.class);

    @Autowired
    @Qualifier("ioBoundExecutor") // 使用I/O密集型线程池
    private Executor asyncExecutor;

    // 保持同步实现
    @Override
    public List<Photo> getLatestPhotos() {
        return photoMapper.findLatestPhotos();
    }

    // 带缓存的异步实现
    @Async("ioBoundExecutor")
    @Cacheable(value = "latestPhotos", key = "'all'", unless = "#result.get().isEmpty()")
    @Override  // 添加@Override注解
    public CompletableFuture<List<Photo>> getCachedLatestPhotosAsync() {
        return CompletableFuture.supplyAsync(() -> {
            logger.debug("开始查询缓存最新照片");
            long startTime = System.currentTimeMillis();
            try {
                List<Photo> photos = photoMapper.findLatestPhotos();
                long duration = System.currentTimeMillis() - startTime;
                logger.debug("缓存最新照片查询完成，耗时: {}ms, 数量: {}", duration, photos.size());
                return photos;
            } catch (Exception e) {
                logger.error("查询缓存最新照片失败", e);
                throw new RuntimeException(e);
            }
        }, asyncExecutor).orTimeout(500, TimeUnit.MILLISECONDS); // 添加500ms超时控制
    }

    // 普通异步实现（不带缓存）
    @Async("ioBoundExecutor")
    public CompletableFuture<List<Photo>> getLatestPhotosAsync() {
        return CompletableFuture.supplyAsync(() -> {
            logger.debug("开始异步查询最新照片");
            long startTime = System.currentTimeMillis();
            try {
                List<Photo> photos = photoMapper.findLatestPhotos();
                long duration = System.currentTimeMillis() - startTime;
                logger.debug("异步查询最新照片完成，耗时: {}ms, 数量: {}", duration, photos.size());
                return photos;
            } catch (Exception e) {
                logger.error("异步查询最新照片失败", e);
                throw new RuntimeException(e);
            }
        }, asyncExecutor).orTimeout(500, TimeUnit.MILLISECONDS); // 添加500ms超时控制
    }


    @Override
    public Photo getPhotoById(String id) {
        if (id == null || id.trim().isEmpty()) {
            return null;
        }
        return photoMapper.findPhotoById(id);
    }

    @Override
    public PhotoUserVO getPhotoUser(String photoId) {
        if (photoId == null || photoId.trim().isEmpty()) {
            return null;
        }
        return photoMapper.findUserByPhotoId(photoId);
    }
    @Override
    public List<Photo> getGreatestPhotos() {
        return photoMapper.findGreatestPhotos();
    }

    @Override
    public ResultVO checkIsLiked(Long currentUserId, Long targetPhotoId) {
        if (currentUserId == null || targetPhotoId == null) {
            return Response.FailResultByMsg("参数错误");
        }
        return Response.OkByData(photoMapper.isLiked(currentUserId, targetPhotoId) > 0);
    }

    @Transactional
    @Override
    public ResultVO like(Long currentUserId, Long targetPhotoId) {
        PhotoUser photoUser = new PhotoUser();
        photoUser.setUserId(currentUserId);
        photoUser.setPhotoId(targetPhotoId);
        photoUserMapper.insert(photoUser);

        Photo photo = photoMapper.findPhotoById(String.valueOf(targetPhotoId));

        photoMapper.updateLikedCount(targetPhotoId, 1);
        userInfoMapper.updateLikedCount(photo.getUserId(), 1);

        return Response.OkByMsg("点赞成功");
    }

    @Transactional
    @Override
    public ResultVO dislike(Long currentUserId, Long targetPhotoId) {
        PhotoUser photoUser = new PhotoUser();
        photoUser.setUserId(currentUserId);
        photoUser.setPhotoId(targetPhotoId);

        QueryWrapper<PhotoUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", currentUserId)
                .eq("photo_id", targetPhotoId);

        photoUserMapper.delete(wrapper);

        Photo photo = photoMapper.findPhotoById(String.valueOf(targetPhotoId));

        photoMapper.updateLikedCount(targetPhotoId, -1);
        userInfoMapper.updateLikedCount(photo.getUserId(), -1);

        return Response.OkByMsg("取消点赞");
    }
}